<template>
    <div class="app-container">
        <!-- 顶部操作按钮区域 -->
        <div style="margin-bottom: 16px; display: flex; gap: 8px;">
            <!-- 新增按钮 -->
            <el-button type="primary" @click="openAdd" :icon="Plus" plain>新增</el-button>
            <!-- 修改按钮（需要选中行才可用） -->
            <el-button type="success" :disabled="!selectedRow" @click="openEdit" :icon="Edit" plain>修改</el-button>
            <!-- 删除按钮（需要选中行才可用） -->
            <el-button type="danger" :disabled="!selectedRow" @click="handleDelete" :icon="Delete" plain>删除</el-button>
        </div>

        <!-- 待处理任务列表 -->
        <!-- 使用标签标识列表类型 -->
        <el-tag type="">待处理任务列表</el-tag>
        <!-- 表格展示待处理任务数据 -->
        <el-table :data="pendingList" style="margin-bottom: 24px;" v-loading="loading"
            @selection-change="handleSelectionChange">
            <!-- 多选列 -->
            <el-table-column type="selection" width="55" />
            <!-- 客户姓名列 -->
            <el-table-column prop="name" label="客户姓名" width="100" />
            <!-- 手机号列 -->
            <el-table-column prop="phone" label="手机号" width="100" />
            <!-- 渠道名称列 -->
            <el-table-column prop="channelName" label="渠道名称" width="100" />
            <!-- 活动名称列 -->
            <el-table-column prop="activityName" label="活动名称" width="100" />
            <!-- 课程名称列 -->
            <el-table-column prop="courseName" label="课程名称" width="100" />
            <!-- 合同金额列 -->
            <el-table-column prop="contractPrice" label="合同金额" width="100" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button link @click="openDetail(scope.row)">查看</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 已提交未审批任务列表 -->
        <el-tag type="success">已提交未审批任务列表</el-tag>
        <el-table :data="committedList" style="margin-bottom: 24px;" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="客户姓名" width="100" />
            <el-table-column prop="phone" label="手机号" width="100" />
            <el-table-column prop="channelName" label="渠道名称" width="100" />
            <el-table-column prop="activityName" label="活动名称" width="100" />
            <el-table-column prop="courseName" label="课程名称" width="100" />
            <el-table-column prop="contractPrice" label="合同金额" width="100" />
        </el-table>

        <!-- 已审批任务列表 -->
        <el-tag type="danger">审批完成任务列表</el-tag>
        <el-table :data="approvedList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="客户姓名" width="100" />
            <el-table-column prop="phone" label="手机号" width="100" />
            <el-table-column prop="channelName" label="渠道名称" width="100" />
            <el-table-column prop="activityName" label="活动名称" width="100" />
            <el-table-column prop="courseName" label="课程名称" width="100" />
            <el-table-column prop="contractPrice" label="合同金额" width="100" />
            <!-- 备注信息列 -->
            <el-table-column prop="reason" label="备注信息" />
            <!-- 操作列：查看详情和预览 -->
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button link :icon="View" type="" @click="openDetail(scope.row)">查看</el-button>
                    <el-button link :icon="Document" @click="openPreview(scope.row)">预览</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑合同弹窗 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="700px">
            <!-- 表单区域 -->
            <el-form :model="form" :rules="rules" ref="formRef" label-width="110px">
                <!-- 第一行：手机号和客户姓名 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入手机号" @keyup="onPhoneInput" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="name">
                            <el-input v-model="form.name" placeholder="请输入客户姓名" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第二行：渠道来源和活动信息 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="渠道来源" prop="channelId">
                            <el-select v-model="form.channelId" placeholder="渠道来源" disabled>
                                <el-option v-for="item in channelList" :key="item.channelId || item.id"
                                    :label="item.channelName || item.name" :value="item.channelId || item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活动信息" prop="activityId">
                            <el-select v-model="form.activityId" placeholder="活动信息" disabled>
                                <el-option v-for="item in activityList" :key="item.activityId || item.id"
                                    :label="item.activityName || item.name" :value="item.activityId || item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第三行：课程分类和购买课程 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="课程分类" prop="courseId">
                            <el-select v-model="form.courseId" placeholder="课程分类" disabled>
                                <el-option v-for="item in courseList" :key="item.courseId || item.dictValue"
                                    :label="item.courseName || item.dictLabel"
                                    :value="item.courseId || item.dictValue" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="购买课程" prop="courseName">
                            <el-input v-model="form.courseName" placeholder="请输入课程名称" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第四行：审批部门和审批人 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="审批部门" prop="approveDeptId">
                            <!-- 树形选择器选择部门 -->
                            <el-tree-select v-model="form.approveDeptId" :data="deptTree" placeholder="请选择归属部门"
                                :props="{ value: 'id', label: 'label', children: 'children', emitPath: false, checkStrictly: true }"
                                check-strictly :show-checkbox="false" :render-after-expand="false" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="审批人" prop="approveUserId">
                            <el-select v-model="form.approveUserId" placeholder="选择用户">
                                <el-option v-for="item in userList" :key="item.userId || item.id"
                                    :label="item.userName || item.name" :value="item.userId || item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第五行：合同价格和合同原件 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="合同价格" prop="contractPrice">
                            <!-- 数字输入框 -->
                            <el-input-number v-model="form.contractPrice" :min="0" style="width: 70%"
                                :disabled="autoDisabled" :step="100" placeholder="请输入合同金额"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="合同原件" prop="filePath">
                            <!-- 文件上传组件 -->
                            <el-upload class="upload-demo" action="/tienchin/contract/upload" :show-file-list="false"
                                :on-success="handleUploadSuccess" :before-upload="beforeUpload" :headers="uploadHeaders"
                                :data="{}">
                                <el-button>选择合同原件</el-button>
                            </el-upload>
                            <!-- 显示上传成功的文件路径 -->
                            <div v-if="form.filePath" style="margin-top: 4px; color: #888; font-size: 12px;">{{
                                form.filePath }}
                            </div>
                            <!-- 上传提示 -->
                            <div style="color: #888; font-size: 12px;">合同原件大小不能超过 5MB.</div>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- 弹窗底部按钮 -->
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 合同详情弹窗 -->
        <el-dialog title="合同详情" v-model="detailVisible" width="900px">
            <!-- 使用栅格系统展示合同详情 -->
            <el-row>
                <el-col :span="8"><b>合同编号</b>
                    <div>{{ detail.contractId }}</div>
                </el-col>
                <el-col :span="8"><b>客户手机号码</b>
                    <div>{{ detail.phone }}</div>
                </el-col>
                <el-col :span="8"><b>客户姓名</b>
                    <div>{{ detail.name }}</div>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8"><b>课程分类</b>
                    <div>游泳类</div>
                </el-col>
                <el-col :span="8"><b>课程名称</b>
                    <div>{{ detail.activityName }}</div>
                </el-col>
                <el-col :span="8"><b>渠道名称</b>
                    <div>{{ detail.channelName }}</div>
                </el-col>


            </el-row>
            <el-row>
                <el-col :span="8"><b>课程</b>
                    <div>{{ detail.activityName }}</div>
                </el-col>
                <el-col :span="8"><b>合同状态</b>
                    <div v-if="detail.status == 2">审批通过</div>
                    <div v-else-if="detail.status == 1">待审批</div>
                    <div v-else-if="detail.status == 0">待提交</div>
                    <div v-else>{{ detail.status }}</div>
                </el-col>
                <el-col :span="8"><b>合同金额</b>
                    <div>{{ detail.contractPrice }}</div>
                </el-col>



            </el-row>
            <el-row>
                <el-col :span="8"><b>课程价格</b>
                    <div>{{ detail.coursePrice }}</div>
                </el-col>
                <el-col :span="8"><b>折扣类型</b>
                    <div v-if="detail.discountType == 2">代金券</div>
                    <div v-else-if="detail.discountType == 1">优惠券</div>
                    <div v-else-if="detail.discountType == 0">无折扣</div>
                    <div v-else>{{ detail.discountType }}</div>
                </el-col>
                <el-col :span="8"><b>审批人</b>
                    <div>{{ detail.approveUserName }}</div>
                </el-col>
            </el-row>
            <template #footer>
                <el-button @click="detailVisible = false">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
// Vue 相关导入
import { ref, reactive, onMounted, watch } from 'vue';
// Element Plus 组件和图标导入
import { ElMessage } from 'element-plus';
import { Plus, Edit, Delete, View, Document } from '@element-plus/icons-vue';
// API 接口函数导入
import {
    addContract,
    updateContract,
    getCommittedTaskList,
    getUnapproveContractList,
    getApprovedContractList,
    getContractDetail,
    getContractByPhone,
    uploadContractFile,
    deleteContractFile,
    getUsersByDept
} from '@/api/contract/Contract';
import { getChannelList, listActivity } from '@/api/activity/activity';
import { getDicts } from '@/api/system/dict/data';
import { deptTreeSelect } from '@/api/system/user';
import { listDept } from '@/api/system/dept';

// ==================== 数据定义区域 ====================
const loading = ref(false); // 表格加载状态
const pendingList = ref([]); // 待处理任务列表数据
const committedList = ref([]); // 已提交未审批列表数据
const approvedList = ref([]); // 已审批列表数据
const channelList = ref([]); // 渠道下拉选项
const activityList = ref([]); // 活动下拉选项
const courseList = ref([]); // 课程下拉选项
const deptTree = ref([]); // 部门树形数据
const userList = ref([]); // 用户下拉选项
const selectedRow = ref(null); // 表格当前选中行
const dialogVisible = ref(false); // 新增/编辑弹窗显示状态
const detailVisible = ref(false); // 详情弹窗显示状态
const dialogTitle = ref(''); // 弹窗标题（新增/编辑）
const formRef = ref(); // 表单引用（用于表单验证）

// 表单数据对象
const form = reactive({
    contractId: undefined, // 合同ID（编辑时使用）
    phone: '', // 手机号
    name: '', // 客户姓名
    channelId: undefined, // 渠道ID
    activityId: undefined, // 活动ID
    courseId: undefined, // 课程ID
    courseName: '', // 课程名称（手动输入）
    approveDeptId: undefined, // 审批部门ID
    approveUserId: undefined, // 审批人ID
    contractPrice: 0, // 合同金额
    filePath: '', // 合同文件路径
    remark: '' // 备注
});

// 合同详情对象
const detail = reactive({
    contractId: '', // 合同ID
    phone: '', // 手机号
    name: '', // 客户姓名
    channelName: '', // 渠道名称
    activityName: '', // 活动名称
    courseName: '', // 课程名称
    coursePrice: 0, // 课程价格
    discountType: 0, // 折扣类型
    approveUserName: '', // 审批人姓名
    status: 0, // 合同状态
    contractPrice: 0, // 合同金额
    filePath: '', // 合同文件路径
    remark: '' // 备注
});


// 表单验证规则
const rules = {
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
    contractPrice: [{ required: true, message: '请输入合同价格', trigger: 'blur' }]
};

// 文件上传请求头（携带token）
const uploadHeaders = { Authorization: localStorage.getItem('token') };

// 控制表单禁用
const autoDisabled = ref(false);

// 手机号输入监听，11位时自动查合同并回显相关字段
const onPhoneInput = async (e: Event) => {
    const val = form.phone;
    if (val && val.length > 10) {
        try {
            const res = (await getContractByPhone(val)).data;
            console.log(res, "手机号")
            if (res) {
                form.name = res.name;
                form.channelId = res.channelId;
                form.activityId = res.activityId;
                form.courseId = res.courseId;
                form.courseName = res.courseName;
            } else {
                form.name = '';
                form.channelId = undefined;
                form.activityId = undefined;
                form.courseId = undefined;
                form.courseName = '';
            }
        } catch {
            form.name = '';
            form.channelId = undefined;
            form.activityId = undefined;
            form.courseId = undefined;
            form.courseName = '';
        }
    } else {
        form.name = '';
        form.channelId = undefined;
        form.activityId = undefined;
        form.courseId = undefined;
        form.courseName = '';
    }
};

// 合同价格加减
const addPrice = () => { form.contractPrice = Math.max(100, form.contractPrice + 100); };
const subPrice = () => { form.contractPrice = Math.max(100, form.contractPrice - 100); };

// ==================== 方法定义区域 ====================
/**
 * 获取页面初始数据
 */
const fetchData = async () => {
    loading.value = true;
    try {
        // 获取待处理任务列表（待实现）
        // pendingList.value = await someApi();

        // 获取已提交未审批列表
        committedList.value = (await getCommittedTaskList()).rows || [];

        // 获取已审批列表（修正：调用 getApprovedContractList）
        approvedList.value = (await getApprovedContractList()).rows || [];
    } finally {
        loading.value = false;
    }
};

/**
 * 打开新增合同弹窗
 */
const openAdd = () => {
    fetchSelectData();
    dialogTitle.value = '添加合同';
    // 重置表单数据
    Object.assign(form, {
        contractId: undefined,
        phone: '',
        name: '',
        channelId: undefined,
        activityId: undefined,
        courseId: undefined,
        courseName: '',
        approveDeptId: undefined,
        approveUserId: undefined,
        contractPrice: 0,
        filePath: '',
        remark: ''
    });
    autoDisabled.value = false;
    dialogVisible.value = true;
};

/**
 * 打开编辑合同弹窗
 */
const openEdit = async () => {
    if (!selectedRow.value) return;
    dialogTitle.value = '编辑合同';
    try {
        const res = await getContractDetail(selectedRow.value.contractId);
        Object.assign(form, res.data || res);
        autoDisabled.value = true;
        dialogVisible.value = true;
    } catch (error) {
        console.error('获取合同详情失败:', error);
        ElMessage.error('获取合同详情失败');
    }
};

/**
 * 处理删除操作
 */
const handleDelete = () => {
    ElMessage.warning('请实现删除逻辑');
};

/**
 * 提交表单（新增/编辑）
 */
const submitForm = () => {
    formRef.value.validate(async (valid: boolean) => {
        if (!valid) return;
        try {
            if (form.contractId) {
                // 执行更新操作
                await updateContract(form);
                ElMessage.success('修改成功');
            } else {
                // 执行新增操作
                await addContract(form);
                ElMessage.success('新增成功');
            }
            dialogVisible.value = false;
            // 刷新表格数据
            fetchData();
        } catch (error) {
            // 错误处理
            console.error('操作失败:', error);
        }
    });
};

/**
 * 打开合同详情弹窗
 * @param row 行数据对象
 */
const openDetail = async (row: any) => {
    try {
        // 获取合同详情
        const res = await getContractDetail(row.contractId);
        // 填充详情数据
        Object.assign(detail, res.data || res);
        detailVisible.value = true;
    } catch (error) {
        console.error('获取详情失败:', error);
        ElMessage.error('获取详情失败');
    }
};

/**
 * 打开合同预览
 * @param row 行数据对象
 */
const openPreview = (row: any) => {
    ElMessage.info('请实现PDF预览功能');
};

/**
 * 文件上传成功回调
 * @param response 上传接口响应数据
 */
const handleUploadSuccess = (response: any) => {
    // 更新文件路径
    form.filePath = response.filePath;
};

/**
 * 文件上传前校验
 * @param file 文件对象
 * @returns 是否允许上传
 */
const beforeUpload = (file: File) => {
    // 检查文件大小（不超过5MB）
    if (file.size > 5 * 1024 * 1024) {
        ElMessage.error('合同原件大小不能超过5MB');
        return false;
    }
    return true;
};

/**
 * 删除合同原件
 */
const handleRemoveFile = async () => {
    if (!form.filePath) return;
    // 假设filePath格式为 /年/月/日/文件名
    const arr = form.filePath.split('/').filter(Boolean);
    if (arr.length >= 4) {
        await deleteContractFile(arr[arr.length - 4], arr[arr.length - 3], arr[arr.length - 2], arr[arr.length - 1]);
        form.filePath = '';
        ElMessage.success('删除成功');
    }
};

// 平铺转树工具
function listToTree(list, parentId = 0) {
  return list
    .filter(item => item.parentId === parentId)
    .map(item => ({
      id: item.deptId,
      label: item.deptName,
      children: listToTree(list, item.deptId)
    }));
}

// 审批部门变化时，动态获取审批人
watch(() => form.approveDeptId, async (val) => {
  if (val) {
    try {
      const res = await getUsersByDept(val);
      userList.value = res.data || [];
    } catch {
      userList.value = [];
    }
  } else {
    userList.value = [];
  }
});

/**
 * 获取下拉数据
 */
const fetchSelectData = async () => {
    try {
        // 下拉数据和部门树并发请求
        const [channelRes, actRes, courseRes, deptRes] = await Promise.all([
            getChannelList(),
            listActivity({}),
            getDicts('course_type'),
            listDept()
        ]);
        // 渠道
        const channelData = Array.isArray(channelRes) ? channelRes :
            (channelRes?.rows && Array.isArray(channelRes.rows)) ? channelRes.rows :
                (channelRes?.data && Array.isArray(channelRes.data)) ? channelRes.data : [];
        channelList.value = channelData.filter(item => item && (item.channelId || item.id));
        // 活动
        const activityData = Array.isArray(actRes) ? actRes :
            (actRes?.rows && Array.isArray(actRes.rows)) ? actRes.rows :
                (actRes?.data && Array.isArray(actRes.data)) ? actRes.data : [];
        activityList.value = activityData.filter(item => item && (item.activityId || item.id));
        // 课程
        const courseData = Array.isArray(courseRes) ? courseRes :
            (courseRes?.rows && Array.isArray(courseRes.rows)) ? courseRes.rows :
                (courseRes?.data && Array.isArray(courseRes.data)) ? courseRes.data : [];
        courseList.value = courseData.filter(item => item && (item.courseId || item.dictValue));
        // 部门树
        let rawTree = deptRes.data || deptRes || [];
        deptTree.value = listToTree(rawTree);
        console.log(deptTree.value, "+++++++++树形结构")
    } catch (error) {
        if (error.code === 'ECONNABORTED') {
            ElMessage.error('请求超时，请检查网络或后端服务！');
        } else {
            ElMessage.error('获取下拉数据失败: ' + (error.message || '未知错误'));
        }
        console.error('fetchSelectData接口异常:', {
            error,
            message: error.message,
            code: error.code,
            stack: error.stack
        });
    }
};

// ==================== 生命周期钩子 ====================
onMounted(() => {
    // 组件挂载时获取数据
    fetchData();
   
});

// 只允许单选编辑
const handleSelectionChange = (rows: any[]) => {
    selectedRow.value = rows.length === 1 ? rows[0] : null;
};
</script>

<style scoped lang="scss">
.app-container {
    padding: 20px;

    .el-card {
        margin-bottom: 20px;

        .el-card__header {
            padding: 15px 20px;
            border-bottom: 1px solid #ebeef5;

            .clearfix {
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
        }
    }

    .detail-item {
        margin-bottom: 15px;

        label {
            font-weight: bold;
            color: #606266;
            margin-right: 10px;
        }

        span {
            color: #303133;
        }
    }

    .dialog-footer {
        text-align: right;
    }

    .upload-demo {
        .el-upload {
            width: 100%;
        }
    }
}
</style>
